package com.liy.framework.common.office.excel;

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import java.util.*;
import java.io.*;

public class ReadExcel
{
    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
    
    public static void main(final String[] args) {
        try {
            new ReadExcel();
            readExcel("H:\\D\u8fbe\u5b9e\u667a\u80fd\\AFC_PM\\05.\u8ba1\u5212\\\u68c0\u6d4b\u4e2d\u5fc3\u5e73\u53f0\u7cfb\u7edf-\u6837\u54c1\u5f00\u53d1\u8ba1\u5212.xlsx");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static List<Map<Integer, Object>> readExcel(final InputStream input, final boolean is2010) {
        final List<Map<Integer, Object>> listMap = new ArrayList<Map<Integer, Object>>();
        Map<Integer, Object> map = null;
        try {
            final Workbook wb = (Workbook)(is2010 ? new XSSFWorkbook(input) : new HSSFWorkbook(input));
            final Sheet sheet = wb.getSheetAt(0);
            final Iterator<Row> rows = (Iterator<Row>)sheet.rowIterator();
            while (rows.hasNext()) {
                map = new HashMap<Integer, Object>();
                final Row row = rows.next();
                final Iterator<Cell> cells = (Iterator<Cell>)row.cellIterator();
                if (row.getRowNum() == 26) {}
                while (cells.hasNext()) {
                    Object val = null;
                    final Cell cell = cells.next();
                    switch (cell.getCellType()) {
                        case 0: {
                            val = cell.getNumericCellValue();
                            break;
                        }
                        case 1: {
                            val = cell.getStringCellValue();
                            break;
                        }
                        case 4: {
                            val = cell.getBooleanCellValue();
                            break;
                        }
                        case 2: {
                            val = cell.getCellFormula();
                            break;
                        }
                        default: {
                            val = "";
                            break;
                        }
                    }
                    map.put(cell.getColumnIndex(), val);
                }
                listMap.add(map);
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return listMap;
    }
    
    public static List<Map<Integer, Object>> readExcel(final String fileName) throws Exception {
        final InputStream input = new FileInputStream(fileName);
        return readExcel(input, fileName.endsWith("xlsx"));
    }
}
